/**
 * 
 */
package com.rf.richfitwheel.workflow.controller;

import java.util.List;
import java.util.Map;

import com.rf.richfitwheel.admin.sys.vo.UserVO;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.rf.richfitwheel.admin.annotation.ModifyAnnotaionFactory;
import com.rf.richfitwheel.admin.annotation.UserOperateLog;
import com.rf.richfitwheel.admin.utils.UserUtil;
import com.rf.richfitwheel.common.exception.BusinessException;
import com.rf.richfitwheel.common.utils.PageUtils;
import com.rf.richfitwheel.common.utils.R;
import com.rf.richfitwheel.workflow.entity.TaskParam;
import com.rf.richfitwheel.workflow.entity.TaskVO;
import com.rf.richfitwheel.workflow.service.LovelyTaskService;

/**
 * @author hushouquan
 *
 */
@RequestMapping("/task")
@RestController
public class TaskController {

	protected static final Logger log = LoggerFactory.getLogger(TaskController.class);
	
	@Autowired
    private LovelyTaskService lovelyTaskService;
	
	/**
     * <p>Title: 流程提交方法，供前端和外部feign调用</p>
     * <p>Description: </p>
     *
     * @param params
     * @return
     */
    @UserOperateLog(module = "工作流", methods = "subminTask", description = "提交流程", functionNo = "104016")
    @PostMapping(value = "/subminTask")
    @ResponseBody
    public R subminTask(@RequestBody TaskParam params) {
        try {
			ModifyAnnotaionFactory.newInstance().ModifyAnnotation(getClass(), UserOperateLog.class, "subminTask", "bussid", params.getTaskId() == null ? "" : params.getTaskId(), params.getClass());
            UserVO user = UserUtil.getUser() == null ? UserUtil.getSystem() : UserUtil.getUser();
			if(params.getUser() == null) {
				params.setUser(user);
			}
			TaskParam rp = lovelyTaskService.subminTask(params, user);
			return R.ok().put("params", rp);
		} catch (Exception e) {
			log.error(" 流程提交失败", e);
			return R.error(" 流程提交");
		}
    }
    
    /**
     * 我的待办流程
     *
     * @param params
     * @return
     */
    @GetMapping("/todoList")
    public PageUtils todoList(@RequestParam Map<String, Object> params) {
        UserVO user = UserUtil.getUser();
    	if (user == null) {
            log.error("无法获取登录用户信息");
            return new PageUtils();
        }
        PageUtils pageUtils = lovelyTaskService.getToDoList(params, user);
        return pageUtils;
    }
    
    /**
     * <p>Title: 授权处理流程列表</p>
     * <p>Description: 别人授权给自己处理的流程</p>
     *
     * @param params
     * @return
     */
    @GetMapping("/authorizationTaskList")
    public PageUtils authorizationTaskList(@RequestParam Map<String, Object> params) {
        UserVO user = UserUtil.getUser();
        if (user == null) {
            log.error("无法获取登录用户信息");
            return new PageUtils();
        }
        params.put("sessionUserId", user.getId());
        params.put("tenantIds", user.getTenantId());
        PageUtils pageUtils = lovelyTaskService.getAuthorizationTaskList(params);
        return pageUtils;

    }
    
    /**
     * <p>Title: 我参与的流程</p>
     * <p>Description: </p>
     *
     * @param page
     * @param limit
     * @param dataForm
     * @return
     */
    @GetMapping("/queryParticipationProcessList")
    PageUtils queryParticipationProcessList(String page, String limit, String dataForm) {
        UserVO user = UserUtil.getUser();
        // List<Map<String, Object>> result = new LinkedList<Map<String, Object>>();

        if (user == null) {
            return null;
        }
        String userId = user.getId();

        // 查询我参与的流程
        PageUtils pageUtils = lovelyTaskService.queryParticipationProcessList(page, limit, dataForm, userId);

        return pageUtils;
    }
    

    /**
     * 查询当前任务节点信息
     * @param taskId
     * @return
     */
    @GetMapping("/getTaskNodeInfo/{taskId}")
    public R getTaskNodeInfo(@PathVariable("taskId") String taskId){
//    	TaskFormData taskFormData = null;
        try {
        	Map<String, Object> taskFormData = lovelyTaskService.getTaskNodeInfo(taskId);
        	TaskVO task= new TaskVO((Task) taskFormData.get("task"));
            return R.ok().put("task", task).put("formProperties", taskFormData.get("formProperties"));
        } catch (BusinessException e) {
            log.error(e.getMessage(), e);
            return  R.error(e.getMessage());
        } catch (Exception e) {
            log.error("获取流程节点信息失败", e);
            return  R.error("获取流程节点信息失败");
        }
    }

    /**
	 * 根据业务id查询流程处理记录
	 * @param params
	 * @return
	 */
    @GetMapping("/getHisTaskByBusNo")
    public R getHisTaskByBusNo(@RequestParam Map<String, Object> params){
        String busNo=params.get("busNo")!=null?params.get("busNo").toString():"";
        List<Map<String, Object>> list = lovelyTaskService.getApproveHistoryByBusNo(busNo);
        return R.ok().put("result", list);
    }
    
    /**
	 * 根据流程实例id查询流程处理记录
	 * @param processId
	 * @return
	 */
    @GetMapping("/getHisTaskByProcessId/{processId}")
    public R getHisTaskByProcessId(@PathVariable("processId") String processId){
        List<Map<String, Object>> list = lovelyTaskService.getApproveHistoryByProcessId(processId);
        return R.ok().put("result", list);
    }
    
    /**
     * 获取可退回节点
     * @param params
     * @return
     */
    @GetMapping("/getRetractNode")
	public R getRetractNode(@RequestParam Map<String, Object> params){

		String processId=params.get("processId")!=null?params.get("processId").toString():"";

		String taskDefinitionKey=params.get("taskDefinitionKey")!=null?params.get("taskDefinitionKey").toString():"";

		String processDefinitionId=params.get("processDefinitionId")!=null?params.get("processDefinitionId").toString():"";

		List<Map<String, Object>> list = lovelyTaskService.getRetractNode(processId,taskDefinitionKey,processDefinitionId);

		return R.ok().put("result", list);
	 }
    
    /**
     * 获取审批意见
     * @param taskId
     * @return
     */
    @GetMapping(value = "/getApproveAdviceByTaskId/{taskId}")
    public R getApproveAdviceByTaskId(@PathVariable("taskId") String taskId){
        String  approveAdvice = lovelyTaskService.getApproveAdviceByTaskId(taskId);
        return R.ok().put("textAdvice", approveAdvice);
    }
    
    /**
     * 根据流程实例id查询当前用户参与过的节点，不包含撤回和终止的节点
     * @param processid 流程实例id
     * @return
     */
    @GetMapping(value = "/getCanRecallNode/{processid}")
    public R getCanRecallNode(@PathVariable("processid") String processid){
        List<Map<String, Object>> list = lovelyTaskService.getCanRecallNode(processid, UserUtil.getUser());
        return R.ok().put("recallList", list);
    }
    
    /**
     * 参与人撤回流程
     * @param params {'processId': 流程实例id,
     *  'recallNodeKey': 要撤回的节点key,
     *  'deleteReason': 撤回原因
     *  }
     * @return
     * @throws Exception
     */
    @UserOperateLog(module = "工作流", methods = "recallMaster", description = "撤回流程")
    @GetMapping("/recallMaster")
    public R recallMaster(@RequestParam Map<String, Object> params) throws Exception {
        try {
        	lovelyTaskService.recallMaster(params, UserUtil.getUser(), UserUtil.getSystem());
            return R.ok();
        } catch (BusinessException e) {
            log.error(e.getMessage(), e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return R.error("流程撤回失败！");
        }
    }
    

    /**
     * 流程查询、分页
     * @param params
     * @return
     */
    @GetMapping("/allProcessList")
    public R allProcessList(@RequestParam Map<String, Object> params) {

    	PageUtils pageUtils = lovelyTaskService.allProcessList(params, UserUtil.getUser());
    	
        return R.ok().put("page", pageUtils);
    }
    
    /**
     * 删除运行中流程
     * <p>Title: deleteProcess</p>
     * <p>Description: </p>
     *
     * @param params
     * @return
     */
    @UserOperateLog(module = "工作流", methods = "deleteProcess", description = "终止流程流程")
    @GetMapping("/deleteProcess")
    public R deleteProcess(@RequestParam Map<String, Object> params) {
        String processid = params.get("processid") != null ? params.get("processid").toString() : "";

        String deleteReason = params.get("deleteReason") != null ? params.get("deleteReason").toString() : "";
        
        try {
        	lovelyTaskService.deleteProcess(processid, deleteReason, UserUtil.getUser());
        } catch (BusinessException e) {
            log.error(e.getMessage(), e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            log.error("流程终止失败", e);
            return R.error("终止失败！");
        }
        return R.ok();
    }


    
    /**
     * 暂存审批意见
     * @param params
     * @return
     */
    @UserOperateLog(module = "工作流", methods = "saveApproveAdvice", description = "修改流程审批意见")
    @PostMapping("/saveApproveAdvice")
    public R saveApproveAdvice(@RequestBody Map<String, Object> params){
        try {
            UserVO user = UserUtil.getUser();
            if(user == null){
                throw new BusinessException("需要登录才能操作");
            }
            String taskId = params.get("taskId") == null ? null : params.get("taskId").toString();
            if(taskId == null){
                throw new BusinessException("请传入流程任务id");
            }
            String approveAdvice = params.get("approveAdvice") == null ? null : params.get("approveAdvice").toString();
            if(approveAdvice == null){
                throw new BusinessException("请录入处理意见");
            }
            String authCatagory = params.get("authCatagory") == null ? null : params.get("authCatagory").toString();
            String owner = params.get("owner") == null ? null : params.get("owner").toString();
            //给日志注解传入业务id
            ModifyAnnotaionFactory.newInstance().ModifyAnnotation(TaskController.class, UserOperateLog.class, "saveApproveAdvice", "bussid", taskId, Map.class);
            lovelyTaskService.saveApproveAdvice(user.getId(), taskId, approveAdvice, authCatagory, owner);
            return R.ok();
        } catch (BusinessException e) {
            log.error(e.getMessage(), e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return R.error("暂存处理意见失败");
        }
    }

    /**
     * 根据当前流程任务id查询流程变量
     * 
     * @param taskId
     * @return
     */
    @GetMapping(value = "/getTaskParamByTaskId/{taskId}")
    public R getTaskParamByTaskId(@PathVariable("taskId") String taskId) {
        Map<String, Object> wf_param = lovelyTaskService.getTaskParamByTaskId(taskId);
        return R.ok().put("wf_param", wf_param);
    }
}
